package com.xxx;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		
		try {
			//判断表单中是否有multipart属性
			boolean isMultipart=ServletFileUpload.isMultipartContent(request);
			if(isMultipart){
				//创建工厂类
				FileItemFactory factory=new DiskFileItemFactory();
				//创建解析器
				ServletFileUpload upload=new ServletFileUpload(factory);
				//设置单个文件大小
				//upload.setSizeMax(20480);
				//通过parseRequest解析form表单中所有请求字段，并保存到item集合中
				List<FileItem> items=upload.parseRequest(request);
				//遍历items数据
				Iterator<FileItem> iter=items.iterator();
				while(iter.hasNext()){
					FileItem item=iter.next();
					String itemName=item.getFieldName();
					//判断请求字段是普通文本项<true>还是文件项<false>
					if(item.isFormField()){
						
					}else{
						//获取文件名、文件内容、指定文件路径、文件后缀
						String fileName=item.getName();
						System.out.println(fileName);
						String path=request.getSession().getServletContext().getRealPath("upload");
						System.out.println(path);
						File file=new File(path,fileName);
						item.write(file);
						System.out.println(fileName+"上传成功");
					}
				}
			} 
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
		
			
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
